# libs ----
library(sf)
library(geomander)
library(tidyverse)
library(redist)
library(ppmf)
library(grid)
library(patchwork)
library(wacolors)

# helper ----
source('R/00_custom_functions.R')

# data ----
shp <- read_rds(file = 'data/DE/de.Rds')
shp <- shp %>% mutate(sld_up = as.numeric(sld_up), sld_low = as.numeric(sld_low))
map_cen <- redist_map(shp, existing_plan = sld_up, pop_tol = 0.05)
map_v4 <- redist_map(shp, existing_plan = sld_up, pop_tol = 0.05, total_pop = v4_pop)
map_v12 <- redist_map(shp, existing_plan = sld_up, pop_tol = 0.05, total_pop = v12_pop)
map_v19 <- redist_map(shp, existing_plan = sld_up, pop_tol = 0.05, total_pop = v19_pop)

# random.org ----
set.seed(7180)

# sim! ----
plans_cen <- redist_smc(map = map_cen, nsims = 1e4)
plans_v4  <- redist_smc(map = map_v4, nsims = 1e4)
plans_v12 <- redist_smc(map = map_v12, nsims = 1e4)
plans_v19 <- redist_smc(map = map_v19, nsims = 1e4)

if (FALSE) {
    pm_cen = plan_distances(filter(plans_cen, as.integer(draw) <= 100), ncores=8)
    pm_v4 = plan_distances(filter(plans_v4, as.integer(draw) <= 100), ncores=8)
    pm_v12 = plan_distances(filter(plans_v12, as.integer(draw) <= 100), ncores=8)
    pm_v19 = plan_distances(filter(plans_v19, as.integer(draw) <= 100), ncores=8)

    summary(c(pm_cen))
    summary(c(pm_v4))
    summary(c(pm_v12))
    summary(c(pm_v19))
}

saveRDS(plans_cen, 'data/DE/sim/plans_cen.Rds', compress = 'xz')
saveRDS(plans_v4,  'data/DE/sim/plans_v4.Rds', compress = 'xz')
saveRDS(plans_v12, 'data/DE/sim/plans_v12.Rds', compress = 'xz')
saveRDS(plans_v19, 'data/DE/sim/plans_v19.Rds', compress = 'xz')
